<?php

/**
 * tongyong.php
 *
 * Author: netman
 * DateTime:  2023/10/17 10:37
 */
class Service_Api_Tongyong extends Contract_Api_Product
{
    use Trait_Api_Tongyong;
    use Trait_Api_Common;

    /**
     * @var Service_Api_Fenxiao
     */
    private $fenxiao_service = null;

    public function __construct()
    {
        $this->fenxiao_service = new Service_Api_Fenxiao();
    }

    /**
     * 产品搜索
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/11 17:47
     */
    function search(array $params = array()): array
    {
        $mid      = $params['mid'];
        $typeid   = (int)$params['type_id'];//扩展产品id
        $destpy   = $params['destpy'];//目的地拼音
        $sorttype = $params['sorttype'];//排序方式
        $attrid   = $params['attrid'];//筛选id
        $keyword  = $params['keyword'];//关键词
        $page     = $params['page'];//页数
        $page     = empty($page) ? 1 : $page;
        $pagesize = $params['pagesize'] ? $params['pagesize'] : 10;
        $offset   = $pagesize * ($page - 1);

        if (!empty($destpy)) {
            $dest_id = DB::select('id')->from('destinations')->where('pinyin', '=', $destpy)->execute()->get('id');
            $builder = DB::select(DB::expr("sline_a.*,(IFNULL(`sline_a`.bookcount,0)+IFNULL(`sline_member_order_statistic`.sell_num,0)) AS sell_num"))->from(array('model_archive', 'a'))->join(array('kindorderlist', 'b'), 'left')
                ->on('a.id', '=', 'b.aid')
                ->on('b.typeid', '=', $typeid)
                ->on('b.classid', '=', (int)$dest_id);
        } else {
            $builder = DB::select("a.*")->from(array('model_archive', 'a'))->join(array('allorderlist', 'b'), 'left')
                ->on('a.id', '=', 'b.aid')
                ->on('b.typeid', '=', $typeid);
        }
        // 提前处理真实购买量
        $builder->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_a`.id'))
            ->on('member_order_statistic.type_id', '=', $typeid);

        $builder->where('a.ishidden', '=', 0)->and_where('a.typeid', '=', $typeid);
        //关键词
        if (!empty($keyword)) {
            $builder->and_where('a.title', 'like', '%' . $keyword . '%');
        }
        //按属性
        if (!empty($attrid)) {
            $builder->and_where(DB::expr($this->get_attr_where($params['attrid'])));
        }
        if (!empty($dest_id)) {
            $builder->and_where(DB::expr(" AND FIND_IN_SET($dest_id,sline_a.kindlist) "));
        }

        //排序
        switch ($sorttype) {
            case 1:
                $builder->order_by(DB::expr("sline_a.price asc"));
                break;
            case 2:
                $builder->order_by(DB::expr("sline_a.price desc"));
                break;
            case 3:
                $builder->order_by(DB::expr("sell_num desc"));
                break;
            case 4:
                $builder->order_by(DB::expr("sline_a.satisfyscore desc"));
                break;
            default:
                $builder->order_by(DB::expr(" IFNULL(sline_b.displayorder,9999) ASC"));
                break;
        }
        $total = $builder->execute()->count();
        $arr   = $builder->offset($offset)->limit($pagesize)->execute()->as_array();
        $arr   = $this->format_tongyong($arr);
        if (!empty($arr)) {
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance($typeid, array('mid' => $mid));
            foreach ($arr as &$v) {
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }

        return array(
            'total' => $total,
            'list' => $arr
        );
    }

    /**
     * 产品详情
     * @param array $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/11 16:39
     */
    function info(array $params = array()): array
    {

        $product_id = $params['product_id'];
        $typeid     = $params['type_id'];//模型id
        $info       = Model_Tongyong::detail(0, $typeid, 0, $product_id);
        if (!$info) {
            throw new Exception('未找到产品信息');
        }

        //产品图片
        $info['piclist'] = Product::pic_list($info['piclist']);
        $p               = array();
        foreach ($info['piclist'] as &$pic) {
            $pi = $this->img_url($pic[0]);
            array_push($p, $pi);
        }
        $info['piclist'] = $p;
        $info['litpic']  = $this->img_url($info['litpic'],750,750);
        //属性列表
        $info['attrlist'] = Model_Tongyong::product_attr($info['attrid'], $typeid);
        //最低价
        $info['price'] = Model_Tongyong::get_minprice($info['id'], $info);
        //市场价
        $info['sellprice'] = Model_Tongyong::get_min_sellprice($info['id']);
        //满意度
        $info['score'] = St_Functions::get_satisfy($typeid, $info['id'], $info['satisfyscore']);
        //$info['satisfyscore'] = St_Functions::get_satisfy($typeid, $info['id'], $info['satisfyscore']);
        //点评数
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], $typeid);
        //销售数量
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], $typeid) + $info['bookcount'];
        //产品编号
        $info['series'] = Product::product_number($info['id'], $typeid);
        //产品图标
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);
        //供应商
        if ($info['supplierlist']) {
            $supplier_shop_service = new Service_Api_Supplier_Shop();
            $info['suppliers']     = $supplier_shop_service->get_shop_info($info['supplierlist']);
        }
        // 内容
        $info['content'] = $this->content_add_domain($info['content']);
        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $info['profit'] = $this->fenxiao_service->get_estimate_profit($typeid, $params['mid'], $info['id'], $info['price']);
        }
        // 积分抵现配置
        $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], $typeid);
        $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
        // 预定送积分
        $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], $typeid);
        $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        //积分评论
        $jifencomment_info         = Model_Jifen::get_used_jifencomment($typeid);
        $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);
        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $coupon_list = Model_Coupon::xcx_get_product_coupon_list($info['id'], $typeid, $params['mid']);
            $coupons     = [];
            foreach ($coupon_list as $coupon) {
                $coupons[] = $this->filter_data(array('id', 'name'), $coupon);
            }
            $info['coupon_list'] = $coupons;
        }
        //供应商
        if ($info['supplierlist']) {
            $info['suppliers'] = DB::select('suppliername', 'id')->from('supplier')->where('id', '=', $info['supplierlist'])->execute()->current();
        }
        //扩展字段信息
        $extend_info = Model_Tongyong::extend($info['id'], $typeid);
        foreach ($extend_info as &$v) {
            $v['content'] = $this->content_add_domain($info['content']);
        }
        $minsuit     = $this->get_min_suit($info['id'], $params);//套餐情况

        //介绍
        $params              = array(
            'typeid' => $typeid,
            'productinfo' => $info,
            'onlyrealfield' => 1,
            'pc' => 0,
        );
        $info['detail_list'] = $this->get_content($params);
        return array(
            'minsuit' => $minsuit,
            'info' => $info,
            'extendinfo' => $extend_info
        );

    }

    /**
     * 产品查询条件
     * @return array
     * User: netman
     * Date: 2023/9/11 17:48
     */
    function query_condition(): array
    {


    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/13 16:24
     */
    function create_order(array $params = array()): array
    {
        //会员信息
        $mid         = $params['mid'];
        $member_info = $params['member_info'];
        //套餐id
        $suit_id = $params['suit_id'];
        //联系人
        $linkman = $params['linkman'];
        //手机号
        $linktel    = $params['linktel'];
        $linkidcard = $params['linkidcard'] ?? '';
        //备注信息
        $remark = $params['remark'] ?? '';;
        //产品id
        $product_id = $params['product_id'];
        //使用时间
        $use_date = $params['use_date'];
        //预订数量
        $ding_num  = $params['ding_num'];
        $needJifen = $params['needjifen'];
        $type_id   = $params['type_id'];

        $address_id         = $params['address_id'] ?? 0;
        $envelope_member_id = $params['envelope_member_id'] ?? 0;//红包id

        // 游客信息
        $tourist = $params['tourist'] ?? '';
        if ($tourist) {
            $tourist = json_decode($tourist);
        }
        $info    = ORM::factory('model_archive')->where('id', '=', $product_id)->find()->as_array();
        $suitArr = ORM::factory('model_suit')
            ->where("id=:suitid")
            ->param(':suitid', $suit_id)
            ->find()
            ->as_array();

        $suitArr['dingjin']  = Currency_Tool::price($suitArr['dingjin']);
        $price_info          = DB::select()->from('model_suit_price')
            ->and_where('suitid', '=', $suit_id)
            ->and_where('day', '=', strtotime($use_date))->execute()->current();
        $price_info['price'] = Currency_Tool::price($price_info['price']);
        if (!Model_Tongyong::check_storage($product_id, $ding_num, $suit_id, $use_date)) {
            throw new Exception("库存不足");
        }
        if ($suitArr['paytype'] == '3')//这里补充一个当为二次确认时,修改订单为未处理状态.
        {
            $info['need_confirm'] = 1;
            $info['status']       = 0;
        } else {
            $info['need_confirm'] = 0;
            $info['status']       = 1;
        }
        $info['name']       = $info['title'];
        $info['suit_name']  = $suitArr['suitname'];
        $info['paytype']    = $suitArr['paytype'];
        $info['dingjin']    = $suitArr['dingjin'];
        $info['ourprice']   = $price_info['price'];
        $info['childprice'] = 0;
        $info['usedate']    = $use_date;

        $jifentprice = 0;
        $useJifen    = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], $type_id, $needJifen, $member_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $needJifen;
        }
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment($type_id);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        //自动关闭订单时间
        $auto_close_time = $suitArr['auto_close_time'] ?? 0;
        if ($auto_close_time) {
            $auto_close_time = time() + $auto_close_time;
        }

        $ordersn = Product::get_ordersn($type_id);
        $arr     = array(
            'ordersn' => $ordersn,
            'webid' => 0,
            'typeid' => $type_id,
            'productautoid' => $product_id,
            'productaid' => $info['aid'],
            'productname' => $info['name'],
            'litpic' => $info['litpic'],
            'price' => $info['ourprice'],
            'childprice' => $info['childprice'],
            'jifentprice' => $jifentprice,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,
            'paytype' => (int)$info['paytype'],
            'dingjin' => $info['dingjin'],
            'usedate' => $info['usedate'],
            'departdate' => '',
            'addtime' => time(),
            'memberid' => $mid,
            'dingnum' => $ding_num,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkidcard' => $linkidcard,
            'suitid' => $suit_id,
            'remark' => $remark,
            'status' => $info['status'] ? $info['status'] : 0,
            'usejifen' => $useJifen,
            'needjifen' => $needJifen,
            'receiver_address_id' => $address_id ? (int)$address_id : 0,
            'refund_restriction' => $suitArr['refund_restriction'],//退改条件
            'auto_close_time' => $auto_close_time, //自动关闭订单时间
            'need_confirm' => $info['need_confirm'],
            'suit_name' => $info['suit_name']
        );

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $arr);
        }

        //添加订单
        $out = Model_Api_V2_Order::add_order($arr, 'Model_Model_Archive', $params);
        if ($out['status']) {
            $orderInfo = Model_Member_Order::order_info($ordersn);
            //游客信息保存
            if (!empty($tourist)) {
                $tarr = array();
                foreach ($tourist as $k => $v) {
                    $tarr['orderid']                = $orderInfo['id'];
                    $tarr['tourername']             = $v->linkman;
                    $tarr['sex']                    = $v->sex;
                    $tarr['mobile']                 = $v->mobile;
                    $tarr['cardtype']               = $v->cardtype;
                    $tarr['cardnumber']             = $v->idcard;
                    $tarr['en_first_name']          = $v->en_first_name;
                    $tarr['en_last_name']           = $v->en_last_name;
                    $tarr['nationality']            = $v->nationality;
                    $tarr['cardnumber_expire_date'] = $v->cardnumber_expire_date;
                    $tarr['birth']                  = $v->birth;
                    DB::insert('member_order_tourer', array_keys($tarr))->values(array_values($tarr))->execute();
                }
            }

            // 使用优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $ordersn, $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }

            //添加红包抵扣
            if (St_Functions::is_normal_app_install('red_envelope') && $envelope_member_id) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $ordersn, 13, $orderInfo['memberid']);
            }

            //订单结算信息表数据更新
            Model_Member_Order_Compute::update($orderInfo['ordersn']);

            // 订单创建完成事件
            Hook::trigger('order_created', $orderInfo);

            // 返回订单信息
            $filter_keys = array('id', 'orderid', 'ordersn', 'paytype', 'typeid', 'status');
            return $this->filter_data($filter_keys, $orderInfo);

        } else {
            throw new Exception($out['msg']);
        }

    }


}